<%@ include file="/common/taglibs.jsp" %>
<link rel="stylesheet" type="text/css" href="<c:url value='/css/jquery/flexigrid.pack.css' />" />
<script type="text/javascript" src="<c:url value='/js/jquery/flexigrid.pack.js' />"></script>
<script type="text/javascript" src="<c:url value='/js/util.js'/>"></script>
<script type="text/javascript" src="<c:url value='/js/payment-line-item.js'/>"></script>
<script type="text/javascript" src="<c:url value='/js/jquery/jquery.numeric.js'/>"></script>
<script type="text/javascript" src="<c:url value='/js/jquery/jquery.formatCurrency-1.4.0.pack.js'/>"></script>
<link href="<c:url value='/css/dhtmlxcombo_paylineitem.css' />"	rel="stylesheet" type="text/css" />
<style type="text/css">
	a.dp-choose-date {
		float: left;
		width: 16px;
		height: 16px;
		padding: 0;
		margin: 5px 3px 0;
		display: block;
		text-indent: -2000px;
		overflow: hidden;
		background: url(calendar.png) no-repeat; 
	}
	a.dp-choose-date.dp-disabled {
		background-position: 0 -20px;
		cursor: default;
	}
	/* makes the input field shorter once the date picker code
	 * has run (to allow space for the calendar icon
	 */
	input.dp-applied {
		width: 140px;
		float: left;
	}
  
	
</style>
<script type="text/javascript">
    $(document).ready(
            function() {
                $('#pageTitle').text('<spring:message code="editPaymentrequest.heading.paymentReqProcessing" />');
                
                var cancelRequestedMessage = '<spring:message code="status.payment.process.cancelrequested" />';
                var statusCode = '${paymentrequest.statusCode}';
                if(cancelRequestedMessage == statusCode) {
                    $('#nextActionButton').click(function() {
                    
                        var dialogBody = '';
                        dialogBody += 'A request to cancel this payment request has ';
                        dialogBody += 'been submitted by the originator. Do you want to cancel ';
                        dialogBody += 'the payment request, or continue processing the ';
                        dialogBody += 'payment?';
                        $('<div>' + dialogBody + '</div>').dialog({
                            modal: true,
                            height: 300,
                            width: 400,
                            buttons: 
                                  {
                                    'Cancel' : function() {
                                        var nextactionValue = '<spring:message code="editPaymentrequest.label.prCancel" />';
                                        var nextactionname = '<spring:message code="name.button.nextaction" />';
                                        $(this).dialog('close');
                                        $('#editPaymentrequestForm').append('<input type="hidden" name="' + nextactionname + '" value="' + nextactionValue + '" />');
                                        $('#editPaymentrequestForm').submit();
                                    },
                                    'Continue Processing' : function() {
                                        var nextactionValue = '<spring:message code="name.button.continuepaymentrequest" />';
                                        var nextactionname = '<spring:message code="name.button.nextaction" />';
                                        $(this).dialog('close');
                                        $('#editPaymentrequestForm').append('<input type="hidden" name="' + nextactionname + '" value="' + nextactionValue + '" />');
                                        $('#editPaymentrequestForm').submit();
                                    }
                                  },
                              close: function(event, ui) {
                                  $(this).dialog('destroy');                  
                              }
                        });
                        return false;
                    });
                }
                <c:if test="${showPaymentLineItems}">
                var arr_projects = new Array();
                <c:forEach items="${cipeProjects}" var="project" varStatus="status">
                    var project${status.index} = new Object();
                    project${status.index}.id = '${project.id}';
                    project${status.index}.projectId = '${project.projectId}';
                    project${status.index}.projectType = '${project.projectTypeDesc}';
                    project${status.index}.title = '${project.escapedTitle}';
                    project${status.index}.status = '${project.status}';
                    project${status.index}.region = '${project.escapedRegion}';
                    project${status.index}.country = '${project.escapedCountry}';
                    project${status.index}.acronym = '${project.escapedAcronym}';
                    project${status.index}.formattedStartDate = '${project.formattedProjectStartDate}';
                    project${status.index}.formattedEndDate = '${project.formattedProjectEndDate}';
                    project${status.index}.partnerName = '${project.escapedPartnerName}';
                    project${status.index}.override = '${project.budgetOverride}';
                    project${status.index}.remainingFunds = ${project.remainingFundsPRExcluded};
                    project${status.index}.displayName = '${project.displayName}';
                    arr_projects[${status.index}] = project${status.index};
                </c:forEach>
                var arr_account_codes = new Array();
                <c:forEach items="${accountCodes}" var="accountCode" varStatus="status">
                    var accountCode${status.index} = new Object();
                    accountCode${status.index}.id = '${accountCode.id}';
                    accountCode${status.index}.code = '${accountCode.code}';
                    accountCode${status.index}.accountStatus = '${accountCode.accountStatus}';
                    accountCode${status.index}.description = '<c:out value="${accountCode.escapedDescription}" />';
                    accountCode${status.index}.displayName = '<c:out value="${accountCode.displayName}" />';
                    arr_account_codes[${status.index}] = accountCode${status.index};
                </c:forEach>
                var arr_lineItems = new Array();
                <c:forEach items="${paymentrequest.lineItemBeans}" var="item" varStatus="status">
                    var item${status.index} = new Object();
                    item${status.index}.id = '${item.id}';
                    item${status.index}.accountCodeId = '${item.accountCodeId}';
                    item${status.index}.cipeProjectId = '${item.cipeProjectId}';
                    item${status.index}.lineItemNumber = '${item.lineItemNumber}';
                    item${status.index}.prevAmount = <c:out value="${item.prevAmount}" default="0.0" />;
                    item${status.index}.amount = <c:out value="${item.amount}" default="0.0" />;
                    arr_lineItems[${status.index}] = item${status.index};
                </c:forEach>
                
                var tabIndex = parseInt($('#specialInstructions').attr('tabindex'));

                var paymentLineItem = new com.cipe.cmrs.model.PaymentLineItem('paymentLineItems', arr_projects, arr_account_codes, arr_lineItems, tabIndex, function(totalAmount) {
                    $('#amount').val(totalAmount);
                    $('#amount').formatCurrency('#amountLabel',{colorize: true, negativeFormat: '(-%s%n)'});
                });
    			</c:if>
        		$("#amount").val(${paymentrequest.amount});
        		$('#amount').formatCurrency('#amountLabel',{colorize: true, negativeFormat: '(-%s%n)', roundToDecimalPlace: 2});
                
                $.validator.addMethod("drop_down_required", function(value, element) {
                    return (value != "");
                }, "Please select an option.");
                
                $("#editPaymentrequestForm").validate({
                    rules : {
                        paymentTypeId : {
                            drop_down_required : true
                        },
                        paymentMethod : {
                            drop_down_required : true
                        },
                        payeeId : {
                            drop_down_required : true
                        },
                        purposeOfExpenditure : {
                            required : true
                        }
                    }
                });

                $('#btnSignatureSelection').click(function() {
//                     window.open("<c:url value='/report.do' />", "_blank", "left=20, top=20, width=700, height=700, toolbar=1, resizable=0").focus();
                });
                
                $('#btnOutstandingWireTransfers').click(function() {
                    window.open("<c:url value='/report.do' />", "_blank", "left=20, top=20, width=700, height=700, toolbar=1, resizable=0").focus();
                });
                
                $('#btnOver30days').click(function() {
                    window.open("<c:url value='/report.do' />", "_blank", "left=20, top=20, width=700, height=700, toolbar=1, resizable=0").focus();
                });
                
//                 $('#btnSignatureAllUnpaid').click(function() {
//                     window.open("<c:url value='/secure/signatureSelectionAllUnpaidPdf.do' />").focus();
//                 });
                
                $('#printWireForm').click(function() {
                    window.open("<c:url value='/secure/showBankWireTransferPdf.do' />?paymentRequestId=" + "${paymentrequest.id}", "_blank").focus();
                });
                /*
                    PRV5
                    Print Payment Request' button - There should be a "dynamic button" which changes based on the 'Type' of payment request chosen.
                    1) If the Payment Request Type = "Advance" or "Consultants/Contracts" or "Staff Reimbursements" or "Vendor Invoices" the button should read 'Print Payment Request Form', and should print the standard Payment Request form.
                    2) If the Payment Request Type = "Partner Payment" the button should read 'Print Partner Payment Request Form', and should print the standard Partner Payment Request Form.
                    3) If the Payment Request Type = "Reclass/Liquidation" the button should read 'Print Reclass Form', and should print the standard ReclassForm.        
                */
                $("#paymentTypeId").change(function()
                {
                    if(this.value==1 || this.value==2 || this.value==4 || this.value==6) {
                        $('#printPaymentRequest').text('Print Payment Request Form');
                        $('#printPaymentRequest').css('display','inline');
                    }
                    else if(this.value== 3) {
                        $('#printPaymentRequest').text('Print Partner Payment Request Form');
                        $('#printPaymentRequest').css('display','inline');
                    } else if(this.value == 5){
                        $('#printPaymentRequest').text('Print Reclass Form');
                        $('#printPaymentRequest').css('display','inline');
                    } else {
                        $('#printPaymentRequest').css('display','none');
                    }

        			if (this.value == 3 ? true : previousPaymentTypeId == 3) {
        				var payeeId = "";
        				var payeetype = "";
        				if ($("#payeeId").val() != ''/* && $("#payeeId").val() != null*/) {
        					payeeId = $("#payeeId").val();
        				}
        				if (this.value == 3) {
        					payeetype = "Partner";
        				}

        				loadDataViaAjax("getPayeeList.do", {
        					"payeeId" : payeeId,
        					"payeetype" : payeetype
        				}, parsePayeeListJson);
        			}
        			previousPaymentTypeId = this.value;
                });
                var previousPaymentTypeId = $("#paymentTypeId").val();
                    
                $("#paymentTypeId").change();
                
                $('#printPaymentRequest').click(function() {
                    var reportType = $('#printPaymentRequest').html();
                    if($.trim(reportType) == 'Print Payment Request Form') {
                        window.open("<c:url value='/secure/printPaymentRequestFormPdf.do' />?paymentRequestId=" + "${paymentrequest.id}", "_blank").focus();
                    }
                    if($.trim(reportType) == 'Print Partner Payment Request Form') {
					<c:choose>
						<c:when test="${showPrintPartnerPaymentRequestFormMessage}">
						var htmlString = '<div id="printPartnerPaymentRequestFormMessage"><spring:message code="editPaymentrequest.message.printPartnerPaymentRequestForm" /></div>';
						$(htmlString).dialog({
							title: 'Print Partner Payment Request Form',
							modal: true,
							height: 200,
							width: 300,
							close: function(event, ui) {
								window.open("<c:url value='/secure/printPartnerPaymentRequestPdf.do' />?paymentRequestId=" + "${paymentrequest.id}", "_blank").focus();
								$(this).dialog('destroy');
							},
							buttons: {
								'OK' : function() {
									$(this).dialog('close');
								}
							}
						});
						</c:when>
						<c:otherwise>
						window.open("<c:url value='/secure/printPartnerPaymentRequestPdf.do' />?paymentRequestId=" + "${paymentrequest.id}", "_blank").focus();
						</c:otherwise>
					</c:choose>
                    }
                    if($.trim(reportType) == 'Print Reclass Form') {
                        window.open("<c:url value='/secure/printReclassFormPdf.do' />?paymentRequestId=" + "${paymentrequest.id}", "_blank").focus();
                    }
                });
                
                toggleViewEditMode(true);
                
                <c:choose>
                    <c:when test="${empty canEdit || !canEdit}">
                        toggleButtons(true,$('#editButton'));
                    </c:when>
                    <c:otherwise>                
                        toggleViewEditMode(true);
                        
                        $('#editButton').click(function() {
                            toggleViewEditMode(false);
                        });
                        
                        $('#cancelEditButton').click(function() {
                            var ans = confirm('Are you sure you want to cancel editing this record without saving it?');
                            if (ans) {
                                loadDiv('content', 'processPaymentrequest.do?id=${paymentrequest.id}');
                            }
                        });
                        
                    </c:otherwise>
                </c:choose>
            
            $('#payeeId').change(function() {
                if (this.value != '') {
                    $('#add-paymentrequest-link').val('Edit');
                    $('#payeeDesc').val($(':selected', this).text());
                    loadDataViaAjax("getPayee.do", {
                        "payeeId" : this.value
                    }, function(bean) {
                        $('#payeeAddress').val(bean.completeAddress);
                    });
                } else {
                    $('#add-paymentrequest-link').val('Add');
                    $('#payeeDesc').val('');
                    $('#payeeAddress').val('');
                }
            });
            $('#payeeId').change();
       //prompt dialog box to allow user to enter the rejection date and reason     
            $('#dummyRejectStatusButton').click(function() {
            	var htmlString = '';
            	$('.form_cont').append('<div id="reject-reason-container"></div>');
            	htmlString += '<label><spring:message code="editPaymentrequest.label.reasonForRejection" />:&nbsp;</label><br/>';
          		htmlString += '<textarea id="dummyReasonRejected" style="width: 100%; height: 250px;"></textarea>';
          		 //adding a textbox and a division
                htmlString +='<br>'
                htmlString += '<label><spring:message code="editPaymentrequest.label.daterejected"/>:&nbsp;</label><br/>';
                htmlString +='<input type="text" id="dateText" ></input>';           
                htmlString +='<div id="dateDiv"></div>';
                
         		var ui = $('#reject-reason-container').append(htmlString);
          	  //bind the division with a datepicker
                $('#dateText').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showButtonPanel: true,
                    dateFormat: 'mm/dd/yy',
                    onClose: function(dateText, inst) { 
//                         var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
//                         var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                        $(this).datepicker('setDate', dateText);
                    }
                });

                ui.dialog({
                    title: 'Please Enter Reason And Rejection Date',
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    close: function(event, ui) {
        				$(this).dialog('destroy');
        				 $('#reject-reason-container').remove();
        			},
                    buttons: {
                        "OK": function() {
                            var dateSelected = $('#dateText').val();
                            var reason = $('#dummyReasonRejected').val();
                            $(this).dialog("close");                           
                          
                            if(reason == null || $.trim(reason) == "" ) {
                                alert("Payment Request was not rejected. You must enter a reject reason to reject the payment request.");
                            } 
                            else if(dateSelected==null || dateSelected==""){
                                alert("Payment Request was not rejected. You must select the rejected date");                            	
                            }else {
//                              $('#dateText').datepicker();
                                $('#dateRejected').val(dateSelected);	 
                                $('#reasonrejected').val(reason);
                                $('#reasonrejected').removeAttr('disabled');
                                $('#dateRejected').removeAttr('disabled');
                              	$('#rejectPaymentStatusButton').click();
                            }
                            $('#reject-reason-container').remove();
                        },
                        "Cancel": function() {
                            $(this).dialog("close");
                            $('#reject-reason-container').remove();
                        }
                    }
                });
                ui.dialog('open');
            });
       //prompt dialog box to allow user the enter date of cancelllation 
            $('#dummyCancelPaymentStatusButton').click( function() {
			$('<div>Would you like to cancel the payment request?</div>').dialog({
				modal: true,
				height: 200,
				width: 300,
				dialogClass: 'confirmationDialog',
				buttons: 
			          {
						'Yes' : function() {
							$(this).dialog('close');
							 cancelPaymentDate();
						},
						'No' : function() {
							$(this).dialog('close');
						}
			          },
			  	close: function(event, ui) {
			  		$(this).dialog('destroy');		  		
			  	}
			});
			return false;
		});
       
              function cancelPaymentDate(){
            	var htmlString = '';
            	$('.form_cont').append('<div id="date-cancellation-container"></div>');              	
                htmlString += '<label><spring:message code="editPaymentrequest.label.datecancelled"/>:&nbsp;</label><br/>';
                htmlString +='<input type="text" id="dateText" ></input>';                   
                htmlString +='<div id="dateDiv"></div>';
                htmlString +='<br/>';
                
         		var ui = $('#date-cancellation-container').append(htmlString);
          	  //bind the division with a datepicker
                $('#dateText').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showButtonPanel: true,
                    dateFormat: 'mm/dd/yy',
                    onClose: function(dateText, inst) { 
//                         var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
//                         var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                        $(this).datepicker('setDate', dateText);
                    }
                });

                ui.dialog({
                    title: 'Please Enter Cancellation Date',
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    close: function(event, ui) {
        				$(this).dialog('destroy');
        				 $('#date-cancellation-container').remove();
        			},
                    buttons: {
                        "OK": function() {
                            var dateSelected = $('#dateText').val();
                            $(this).dialog("close");
                            
                            
                           if(dateSelected==null || dateSelected==""){
                                alert("Payment Request was not rejected. You must select the rejected date");                            	
                            }else {
//                              $('#dateText').datepicker();
                                $('#dateCancelled').val(dateSelected);	 
                                $('#dateCancelled').removeAttr('disabled');
                              	$('#cancelPaymentStatusButton').click();
                            }
                            $('#date-cancellation-container').remove();
                        },
                        "Cancel": function() {
                            $(this).dialog("close");
                            $('#date-cancellation-container').remove();
                        }
                    }
                });
                ui.dialog('open');
          	
          }
          //prompt dialog box to allow user the enter date of receive in finance, signature approval,forward for payment and mark as paid
            $('#dummyNextActionButton').click(function(){
              	var htmlString = '';
              	$('.form_cont').append('<div id="date-nextAction-container"></div>');  
              	if('${nextButtonValue}'=="Receive in Finance")
                 	  htmlString += '<label><spring:message code="editPaymentrequest.label.dateToFinanace"/>:&nbsp;</label><br/>';
                else if('${nextButtonValue}'=="Send for Signature Approval")
                      htmlString += '<label><spring:message code="editPaymentrequest.label.dateforwardedforsignature"/>:&nbsp;</label><br/>';
                else if('${nextButtonValue}'=="Forward for Payment")
                      htmlString += '<label><spring:message code="editPaymentrequest.label.datesubmittedforpayment"/>:&nbsp;</label><br/>';  
                else if('${nextButtonValue}'=="Mark as Paid")
                      htmlString += '<label><spring:message code="editPaymentrequest.label.datepaid"/>:&nbsp;</label><br/>';	  
                	  
                	  htmlString +='<input type="text" id="dateText" ></input>';                   
                  htmlString +='<div id="dateDiv"></div>';
                  htmlString +='<br/>';
                  
           		var ui = $('#date-nextAction-container').append(htmlString);
            	  //bind the division with a datepicker
                  $('#dateText').datepicker({
                      changeMonth: true,
                      changeYear: true,
                      showButtonPanel: true,
                      dateFormat: 'mm/dd/yy',
                      onClose: function(dateText, inst) { 
//                           var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
//                           var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                          $(this).datepicker('setDate', dateText);
                      }
                  });

                  ui.dialog({
                      title: 'Please Enter the Date',
                      autoOpen: false,
                      width: 400,
                      modal: true,
                      resizable: false,
                      close: function(event, ui) {
          				$(this).dialog('destroy');
          				 $('#date-nextAction-container').remove();
          			},
                      buttons: {
                          "OK": function() {
                              var dateSelected = $('#dateText').val();
                              $(this).dialog("close");
                              
                              
                             if(dateSelected==null || dateSelected==""){
                                  alert("Payment Request was not rejected. You must select the rejected date");                            	
                              }else {
//                                $('#dateText').datepicker();
					                if('${nextButtonValue}'=="Receive in Finance"){
					                	  $('#dateToFinanace').val(dateSelected);	 
		                                  $('#dateToFinanace').removeAttr('disabled');
					                }else if('${nextButtonValue}'=="Send for Signature Approval"){
					                	  $('#dateforwardedforsignature').val(dateSelected);	 
		                                  $('#dateforwardedforsignature').removeAttr('disabled');					                	
					                }else if('${nextButtonValue}'=="Forward for Payment"){
					                	  $('#datesubmittedforpayment').val(dateSelected);	 
		                                  $('#datesubmittedforpayment').removeAttr('disabled');					                	
					                }else if('${nextButtonValue}'=="Mark as Paid"){
					                	  $('#datePaid').val(dateSelected);	 
		                                  $('#datePaid').removeAttr('disabled');					                	
					                }
                                
                                	$('#nextActionButton').click();
                              }
                              $('#date-nextAction-container').remove();
                          },
                          "Cancel": function() {
                              $(this).dialog("close");
                              $('#date-nextAction-container').remove();
                          }
                      }
                  });
                  ui.dialog('open');
            	
            });
            
            $('.cancel-button').click(function() {
                loadDiv('content', 'refreshDashboard.do');
            });

//             $("#receivedFromAccountingDate").datepicker();
//             $("#dateToFinanace").datepicker();

            $('.list-paymentrequest-link').click(function() {
                loadDiv('content', 'showPayeeList.do');
            });
            $('#instructions-link').click(function() {
                loadDiv('content', 'showInstructionsPaymentReq.do');
            });

            $('.close-button').click(function() {
                if(confirm('Are you sure you want to close the form?')) {
                    window.location = '../secure/showDashboard.do';
                }
             });
            
            $('#save').click(function() {
			<c:choose>
				<c:when test="${showPaymentLineItems}">
                if(paymentLineItem.has6570or6571AccountCode()) {
                    open6570VerifyDialog(function(verified) {
                        $('#sixFiveSeventyVerify').prop('checked', verified);
                        $('#doSave').click();
                    });
                } else {
                    $('#sixFiveSeventyVerify').prop('checked', false);
                    $('#doSave').click();
                }
				</c:when>
				<c:otherwise>
                $('#sixFiveSeventyVerify').prop('checked', false);
                $('#doSave').click();
				</c:otherwise>
			</c:choose>
            });

    		<c:if test="${isAdminUser}">
    		$("#dateToFinanace").removeClass('uneditable');
    		$("#dateforwardedforsignature").removeClass('uneditable');
    		$("#datesubmittedforpayment").removeClass('uneditable');
    		$("#datePaid").removeClass('uneditable');
    		$("#dateRejected").removeClass('uneditable');
    		$("#dateResubmitted").removeClass('uneditable');
    		$("#dateCancelRequested").removeClass('uneditable');
    		$("#dateCancelled").removeClass('uneditable');
    		</c:if>

			$('#editPaymentrequestForm input, #editPaymentrequestForm select, #editPaymentrequestForm textarea').keypress(function(e) {
				if (e.keyCode == 9 || e.keyCode == 13) {// 9 - tab pressed, 13 - enter pressed
					e.preventDefault();
					var tabIndex = $(this).attr('tabindex');
					if (tabIndex == -1 && $(this).is('input[class^="payment-line-item-amount"]')) {
						var startIndex=("payment-line-item-amount").length;
						var index=parseInt(($(this).attr("class")).substring(startIndex));
						tabIndex = $('input[class^="formatted-payment-line-item-amount' + index + '"]').attr('tabindex');
					}
					tabIndex++;// increment tabindex
					var el = $('#editPaymentrequestForm').find('[tabindex=' + tabIndex + ']');
					if (el[0]) {
						<c:if test="${!isAdminUser}">
						var name = el[0].name;
						while (name == "dateToFinanace"
								|| name == "dateforwardedforsignature"
								|| name == "datesubmittedforpayment"
								|| name == "datePaid"
								|| name == "dateRejected"
								|| name == "dateResubmitted"
								|| name == "dateCancelRequested"
								|| name == "dateCancelled") {
							tabIndex++;
							el = $('#editPaymentrequestForm').find('[tabindex=' + tabIndex + ']');
							if (el[0]) {
								name = el[0].name;
							} else {
								return false;
							}
						}
						</c:if>
						el.focus();
					}

					return false;
				}
			});
        });
        function neverSelectionSignature(updating){
        	var oldPopup = Popup;
        	if (updating == undefined || !updating)
        		$('#btnSignatureSelection')[0].onclick = null;
        	else
        		$('#btnSignatureUpdating').unbind('click');
        	$("#neverSelectionPopUp").load('../secure/neverSelectedSignature.do?selectionType=NeverSelected',function(responseText, statusText, xhr){
        		if(statusText=="success"){
        			if (updating == undefined || !updating) Popup.showModal('neverSelectionPopUp',null,null,{'screenColor':'#111111','screenOpacity':.6,'overflow':'auto','height':'900px'});
        			else Popup = oldPopup;
        			$('#btnSignatureUpdating').click(function() {
        				neverSelectionSignature(true);
        			});
        			
        		}
        		if (updating == undefined || !updating)
        			$('#btnSignatureSelection')[0].onclick = function() {
        				neverSelectionSignature(updating);
        			}
        		if(statusText == "error")
                     alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
        	});
        	
        }
        
        function unPaidSignature(updating){
        	var oldPopup = Popup;
        	if (updating == undefined || !updating)
        		$('#btnSignatureAllUnpaid')[0].onclick = null;
        	else
        		$('#btnSignatureUpdating').unbind('click');
        	$("#neverSelectionPopUp").load('../secure/neverSelectedSignature.do?selectionType=UnPaid',function(responseText, statusText, xhr){
        		if(statusText=="success"){
        			if (updating == undefined || !updating) Popup.showModal('neverSelectionPopUp',null,null,{'screenColor':'#111111','screenOpacity':.6,'overflow':'auto','height':'900px'});
        			else Popup = oldPopup;
        			$('#btnSignatureUpdating').click(function() {
        				unPaidSignature(true);
        			});
        			
        		}
        		if (updating == undefined || !updating)
        			$('#btnSignatureAllUnpaid')[0].onclick = function() {
        				unPaidSignature(updating);
        			}
        		if(statusText == "error")
                     alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
        	});
        	
        }
        function open6570VerifyDialog(okListener) {
            var ID_DIALOG_CONTAINER = 'test_ID_DIALOG_CONTAINER';

            var htmlString = '<div><input id="chk6570Verify" type="checkbox" />I verify that the deliverables have been received and accepted in accordance with the terms of the contract for this payment.</div>';
            var ui = $('<div id="' + ID_DIALOG_CONTAINER + '"></div>').append(htmlString);
            ui.dialog({
                modal: true,
                autoOpen : false,
                height: 250,
                width: 300,
                close: function(event, ui) {
                    $(this).dialog('destroy');
                }
            });
            ui.dialog('option', 'buttons', {
                'OK' : function() {
                    var verified = $('#chk6570Verify').prop('checked');
                    $(this).dialog('close');
                    $('#' + ID_DIALOG_CONTAINER).remove();
                    if(okListener) {
                        okListener(verified);
                    }
                },
                'Cancel' : function() {
                    $(this).dialog('close');
                    $('#' + ID_DIALOG_CONTAINER).remove();
                }
            });
            ui.dialog('open');
        }
        
        function toggleInputOrSelectElement(viewMode,elements,val) {
            for(var i = 0; i < elements.length; i++) {
            	if(val==1)
               	  elements[i].disabled = viewMode;
            	else
                  elements[i].readonly = viewMode;

            	if(!viewMode && val==0)
            		$(elements[i]).removeAttr("readonly");
                var className = '';
                if(viewMode) {
                    className = 'text_grey';
                    if(elements[i].className.indexOf("input-full-width-req") != -1) {
                        className = 'input-full-width-req ' + className;    
                    }
                } else {
                    if(elements[i].className.indexOf("input-full-width-req") != -1) {
                        className += 'input-full-width-req text_blue';    
                    } else {
                        className += 'text_white';
                    }
                }
                elements[i].className = className;
            }
        }
        
        function toggleButtons(viewMode, button) {
            if(viewMode) {
                button.attr('disabled','disabled');
                button.removeClass('blue_btn');
                button.addClass('gray_btn');
            } else {
                button.removeAttr('disabled');
                button.removeClass('gray_btn');
                button.addClass('blue_btn');
            }
        }
        
        function toggleViewEditMode(viewMode) {
            var inputs = $('#paymentInfo input[type="text"]:not(.uneditable)');
            var selects = $('#paymentInfo select:not(.uneditable)');
            var textareas = $('#paymentInfo textarea:not(.uneditable)');
            toggleInputOrSelectElement(viewMode,inputs,0);
            toggleInputOrSelectElement(viewMode,selects,1);
            toggleInputOrSelectElement(viewMode,textareas,0);
            
            if(viewMode) {
            	$("#invoiceRequestDate").datepicker('disable');
                <c:if test="${isAdminUser}">
               	$("#dateToFinanace").datepicker("disable");
               	$("#dateforwardedforsignature").datepicker("disable");
               	$("#datesubmittedforpayment").datepicker("disable");
               	$("#datePaid").datepicker("disable");
               	$("#dateRejected").datepicker("disable");
               	$("#dateResubmitted").datepicker("disable");
               	$("#dateCancelRequested").datepicker("disable");
               	$("#dateCancelled").datepicker("disable");
                </c:if>
            } else {
                $("#invoiceRequestDate").datepicker();
                <c:if test="${isAdminUser}">
                $("#dateToFinanace").datepicker();
                $("#dateforwardedforsignature").datepicker();
                $("#datesubmittedforpayment").datepicker();
                $("#datePaid").datepicker();
                $("#dateRejected").datepicker();
                $("#dateResubmitted").datepicker();
                $("#dateCancelRequested").datepicker();
                $("#dateCancelled").datepicker();
                </c:if>
            }
    
            toggleButtons(viewMode,$('#add-paymentrequest-link'));
            toggleButtons(viewMode,$('#cancelEditButton'));
            toggleButtons(viewMode,$('#save'));
            toggleButtons(viewMode,$('#saveAndAddNew'));
            toggleButtons(!viewMode,$('#editButton'));
			<c:if test="${showPaymentLineItems}">
            var lineItemInputs = $('#paymentLineItems input');
            var lineItemSelects = $('#paymentLineItems select');
            for(var i = 0; i < lineItemInputs.length; i++) {
                lineItemInputs[i].readonly = viewMode;
                lineItemInputs[i].disabled = viewMode;
            }
            for(var i = 0; i < lineItemSelects.length; i++) {
                lineItemSelects[i].readonly = viewMode;
                lineItemSelects[i].disabled = viewMode;
            }
			</c:if>
        }

    	function parsePayeeListJson(data) {
    		var $el = $("#payeeId");
    		var payeeId = $el.val();
    		$el.empty(); // remove old options
    		if (data) {
    			$el.append($("<option></option>")
    				.attr("value", "").text("Select"));
    			for (p in data) {
    				$el.append($("<option></option>")
    					.attr("value", data[p]).text(p));
    			}

    			$el.val(payeeId);
    		}
    	}
</script>
<div id="editPaymentrequestDiv">
    <form:form name="editPaymentrequestForm" id="editPaymentrequestForm" cssClass="main_form" action="processPaymentrequest.do?id=${paymentrequest.id}" method="post" modelAttribute="paymentrequest">
        <form:hidden path="id" />
        <form:checkbox id="sixFiveSeventyVerify" path="sixFiveSeventyVerify" cssClass="hiddenElement"/>
        <div class="form_head">
            <a href="#" class="close-button gray_btn floatR" tabindex="-1">Close Form</a>
            <div class="floatL" style="margin-top: 5px; width: 800px;">
                <a href="#" id="btnSignatureAllUnpaid" class="blue_btn" onclick="unPaidSignature();" tabindex="-1"><spring:message code="editPaymentrequest.button.unPaidSelectedSignature"/></a>
                <a href="#" id="btnOver30days" class="blue_btn" onclick="return false;" tabindex="-1">Over 30 days past due</a>
                <a href="http://192.168.1.189:80/reportserver?/OutstandingWireTransform/OutstandingWireTransform&rs:Command=Render" target="_blank">Outstanding Wire Transfers</a>
<!--            <a href="#" id="btnSignatureSelection" class="blue_btn" onclick="return false;" tabindex="-1">Signature Selection Never Selected</a> -->
                <a href="#" id="btnSignatureSelection" class="blue_btn"  onclick="neverSelectionSignature();" tabindex="-1"><spring:message code="editPaymentrequest.button.neverSelectedSignature"/></a>
            </div>
            <div class="floatL" style="margin-top: 5px; width: 800px;">
              <a href="#" id="instructions-link" class="blue_btn" paymentrequestId="${paymentrequest.id}" tabindex="-1"><spring:message code="editPaymentrequest.label.instructions" /></a>
              <a href="#" id="printPaymentRequest" class="blue_btn"  style="display: none;" onclick="return false;" tabindex="-1">&nbsp;</a>
              <a href="#" id="printWireForm" class="uneditable blue_btn" tabindex="-1"><spring:message code="editPaymentrequest.label.printWireForm" /></a>
            </div>            
            <br class="clear" />
        </div>
        <div class="form_cont">
            <table id="paymentInfo" class="fiveColTable" width="100%" cellspacing="1" cellpadding="0">
              <tr>
                <td colspan="5" style="font-size: 16pt; text-align: center;"><spring:message code="editPaymentrequest.heading.availableAction" /></td>
              </tr>
              <tr>
                <td colspan="4" style="text-align: right; padding-right: 30px;">
                <c:choose>
                  <c:when test="${canCancelStatus}">
                    <sj:submit id="cancelPaymentStatusButton" target="editPaymentrequestDiv" cssClass="uneditable"  key="editPaymentrequest.label.cancel" validate="true" tabindex="-1" cssStyle="visibility: hidden; margin: 0; padding: 0; border: 0; float: left; width: 1px;"/>
                    <input type="button" id="dummyCancelPaymentStatusButton" class="uneditable" value='<spring:message code="editPaymentrequest.label.cancel" />' tabindex="-1"/>
                    
                  </c:when>
                  <c:otherwise>
<%--                <sj:submit id="cancelPaymentStatusButton" cssClass="uneditable" target="editPaymentrequestDiv" key="editPaymentrequest.label.cancel" attr="disabled='disabled'" tabindex="-1"/> --%>
                    <input type="button" id="dummyCancelPaymentStatusButton" class="uneditable" disabled="disabled" value='<spring:message code="editPaymentrequest.label.cancel" />' tabindex="-1"/>
                    
                  </c:otherwise>
                </c:choose>
                <c:choose>
                  <c:when test="${canRejectStatus}">
                    <sj:submit id="rejectPaymentStatusButton" target="editPaymentrequestDiv" cssClass="uneditable" key="editPaymentrequest.label.reject" validate="true" tabindex="-1" cssStyle="visibility: hidden; margin: 0; padding: 0; border: 0; float: left; width: 1px;"/>
                    <input type="button" id="dummyRejectStatusButton" class="uneditable" value='<spring:message code="editPaymentrequest.label.reject" />' tabindex="-1"/>
                  </c:when>
                  <c:otherwise>
                    <input type="button" id="dummyRejectStatusButton" class="uneditable"  disabled="disabled" value='<spring:message code="editPaymentrequest.label.reject" />' tabindex="-1"/>
                  </c:otherwise>
                </c:choose>
                <c:if test="${!empty nextButtonValue}">
                  <c:choose>
                    <c:when test="${disableNextButtonValue}">                     
<%--                       <sj:submit id="nextActionButton" cssClass="uneditable" target="content" value="${nextButtonValue}" nameKey="name.button.nextaction" validate="true" attr="disabled='disabled'"/> --%>
                           <input type="button" id="dummyNextActionButton" class="uneditable"  disabled="disabled"  value='${nextButtonValue}>' tabindex="-1"/>
                      
                    </c:when>
                    <c:otherwise>
                      <sj:submit id="nextActionButton"  target="content"  cssClass="uneditable" value="${nextButtonValue}" nameKey="name.button.nextaction" validate="true" tabindex="-1" cssStyle="visibility: hidden; margin: 0; padding: 0; border: 0; float: left; width: 1px;" />
                      <input type="button" id="dummyNextActionButton" class="uneditable"  value='${nextButtonValue}>' tabindex="-1"/>
                      
                    </c:otherwise>
                  </c:choose>
                </c:if>
                </td>
                <td style="padding-right: 20px; text-align: right;">
                  <c:choose>
                    <c:when test="${empty canEdit || !canEdit}">
                      <input id="editButton" type="button" class="gray_btn" value="Edit" disabled="disabled" tabindex="-1">
                    </c:when>
                    <c:otherwise>
                      <input id="editButton" type="button" class="blue_btn" value="Edit" tabindex="-1">
                    </c:otherwise>
                  </c:choose>
                  <input id="cancelEditButton" type="button" class="gray_btn" value="Cancel Edit" disabled="disabled" tabindex="-1">
                  <input id="save" type="button" class="gray_btn" disabled="disabled" value='<spring:message code="editPaymentrequest.button.save" />' tabindex="-1"/>
                  <sj:submit id="doSave" cssClass="hiddenSubmitButton" target="editPaymentrequestDiv" key="editPaymentrequest.button.save" validate="true" tabindex="-1"/>                    
                </td> 
              </tr>
              <tr class="row">
                 <td colspan="5" style="text-align: center;"><%@ include file="/common/messages.jsp"%></td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.paymentIdentifiedInformation" /></td>
                <td class="input-field">
                  <form:input path="id" cssClass="input-full-width text_grey uneditable" readonly="true" tabindex="-1" style="font-size:2em"/>
                  <form:errors path="id" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.dateToFinanace" /></td>
                <td class="input-field">
                <form:input path="dateToFinanace" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="8"/>
                <form:errors path="dateToFinanace" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="label.originator" /></td>
                <td class="input-field">
                <input type="text" value="${paymentrequest.createdBy }" class="input-full-width text_grey uneditable" readonly="readonly" tabindex="-1" />
                <form:errors path="createdBy" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.dateforwardedforsignature" /></td>
                <td class="input-field">
                <form:input path="dateforwardedforsignature" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="9"/>
                <form:errors path="dateforwardedforsignature" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.datecreated" /></td>
                <td class="input-field">
                <form:input readonly="true" path="creationDate" cssClass="input-full-width text_grey uneditable" tabindex="-1"/>
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.datesubmittedforpayment" /></td>
                <td class="input-field">
                <form:input path="datesubmittedforpayment" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="10"/>
                <form:errors path="datesubmittedforpayment" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.responsibleNextAct" /></td>
                <td class="input-field">
                <form:input path="currentlyresponsible" maxlength="100" cssClass="input-full-width text_grey uneditable" readonly="true" tabindex="-1"/>
                <form:errors path="currentlyresponsible" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.datepaid" /></td>
                <td class="input-field">
                <form:input path="datePaid" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="11"/>
                <form:errors path="datePaid" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label" style="color: red"><spring:message code="editPaymentrequest.label.currentStatus" /></td>
                <td class="input-field">
                <span style="color:red"><form:input path="statusCode" maxlength="50" cssClass="input-full-width text_grey uneditable" readonly="true" tabindex="-1"/></span>
                <form:errors path="statusCode" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.daterejected" /></td>
                <td class="input-field">
                <form:input path="dateRejected" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="12"/>
                <form:errors path="dateRejected" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label" style="vertical-align: top;"><spring:message code="editPaymentrequest.label.payee" /></td>
                <td class="input-field" style="vertical-align: top;">
                <form:select path="payeeId" cssStyle="width: 74%;" cssClass="input-full-width-req text_grey" disabled="true" tabindex="1">
                  <form:option value="" label="Select" />
                  <form:options items="${payeeList}" itemValue="id" itemLabel="payeeName" />
                </form:select>
                <form:hidden path="payeeDesc"/>
                <sj:submit id="add-paymentrequest-link" nameKey="editPaymentrequest.button.addEditPayee" cssClass="gray_btn cancel" target="editPaymentrequestDiv" key="label.edit" tabindex="-1"/>
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label" style="vertical-align: top;"><spring:message code="editPaymentrequest.label.rejectedreason" /></td>
                <td class="input-field">
                <form:textarea path="reasonrejected" maxlength="500" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="-1" cssStyle="height: 45px;"/>
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.payeeAddress" /></td>
                <td class="input-field">
                <input id="payeeAddress" type="text" class="text_grey uneditable" readonly="readonly" tabindex="-1" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.dateresubmitted" /></td>
                <td class="input-field">
                <form:input path="dateResubmitted" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="13"/>
                <form:errors path="dateResubmitted" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label">Source Document Type</td>
                <td class="input-field">
                <form:select path="sourceDocumentType" cssClass="input-full-width text_grey" disabled="true" tabindex="2">
                  <form:option value="Invoice" label="Invoice" />
                  <form:option value="Account" label="Account" />
                  <form:option value="Contract" label="Contract" />
                  <form:option value="Reference #" label="Reference #" />
                </form:select>
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.datecancelrequested"/></td>
                <td class="input-field">
                <form:input path="dateCancelRequested" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="14"/>
                <form:errors path="dateCancelRequested" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.invoiceno" /></td>
                <td class="input-field">
                <form:input path="invoicenumber" maxlength="255" cssClass="input-full-width  text_grey" readonly="true" tabindex="3"/>
                <form:errors path="invoicenumber" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.datecancelled" /></td>
                <td class="input-field">
                <form:input path="dateCancelled" cssClass="input-full-width text_grey uneditable"  readonly="true" tabindex="15"/>
                <form:errors path="dateCancelled" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.invoiceRequestDate" /></td>
                <td class="input-field">
                <form:input path="invoiceRequestDate" cssClass="input-full-width text_grey" readonly="true" tabindex="4"/>
                <form:errors path="invoiceRequestDate" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.checkConfirmNumber" /></td>
                <td class="input-field">
                <form:input path="paymentConfirmationNumber" maxlength="50" cssClass="input-full-width text_grey" readonly="true" tabindex="16"/>
                <form:errors path="paymentConfirmationNumber" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.paymentrequesttype" /></td>
                <td class="input-field">
                <form:select path="paymentTypeId" cssClass="input-full-width-req text_grey" disabled="true" tabindex="5">
                  <form:option value="" label="Select" />
                  <form:options items="${paymenttypeList}" itemValue="id" itemLabel="paymenttypename" />
                </form:select>
                <form:errors path="paymentTypeId" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.comments" /></td>
                <td class="input-field">
                <form:input path="comments" maxlength="1000" cssClass="input-full-width text_grey" readonly="true" tabindex="17"/>
                <form:errors path="comments" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.paymentmethod" /></td>
                <td class="input-field"><form:select path="paymentMethod" cssClass="input-full-width-req text_grey" disabled="true" tabindex="6">
                  <form:option value="" label="Select" />
                  <form:option value="Wire" label="Wire" />
                  <form:option value="Check" label="Check" />
                  <%-- Commented due to ERR-24 
                  <form:option value="Other" label="Other" />
                  --%>
                </form:select>
                <form:errors path="paymentMethod" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="editPaymentrequest.label.specialInstructions" /></td>
                <td class="input-field">
                <form:input path="specialInstructions" maxlength="200" cssClass="input-full-width text_grey" readonly="true" tabindex="18"/>
                <form:errors path="specialInstructions" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.purposeOfExpenditure" /></td>
                <td class="input-field">
                <form:input path="purposeOfExpenditure" maxlength="500" cssClass="input-full-width-req text_grey" dir="true" tabindex="7" readonly="true"/>
                <form:errors path="purposeOfExpenditure" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="label.updatedBy" /></td>
                <td class="input-field">
                <input type="text" value="${paymentrequest.updatedBy }" class="input-full-width text_grey uneditable" readonly="readonly" tabindex="27"/>
                <form:errors path="updatedBy" cssClass="error" />
                </td>
              </tr>
              <tr>
                <td class="label"><spring:message code="editPaymentrequest.label.amount" /></td>
                <td class="input-field">
                <form:hidden path="amount" cssClass="input-full-width text_grey uneditable" />
                <input type="text" value="&nbsp;" readonly="readonly"  id="amountLabel" class="text_grey uneditable" tabindex="-1" style="font-size: 2em;"/>
                <form:errors path="amount" cssClass="error" />
                </td>
                <td class="fiveColSpacer">&nbsp;</td>
                <td class="label"><spring:message code="label.updationDate" /></td>
                <td class="input-field">
                <form:input readonly="true" path="updationDate" cssClass="input-full-width text_grey uneditable" tabindex="28"/>
                <form:errors path="updationDate" cssClass="error" />
                </td>
              </tr>
            </table>
			<c:if test="${showPaymentLineItems}">
            <div id="paymentLineItems">
            </div>
			</c:if>
            <div id="actionDate" align="center"  style="display:none;">
            
            </div>
         
        </div>
    </form:form>
    <script type="text/javascript">
        $(document).ready(function() {
            $('table.tablesorter').tablesorter({
                widgets : [ 'zebra' ],
                sortList : [ [ 0, 0 ], [ 1, 0 ] ],
                headers : {
                    10 : {
                        sorter : false
                    }
                }
            });

            $('.edit-paymentrequestaward-link').click(function() {
                loadDiv('content', 'showEditPaymentrequest.do?id=' + $(this).attr('paymentrequestawardId'));
            });
        });
    </script>
</div>

<div id="neverSelectionPopUp" align="center"  style="display:none; ">

</div>
